﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Virvar.Net.Cryptography
{
    public class Decryptor
    {
        Encoding enc = Encoding.Default;
        RSACryptoServiceProvider rsaProvider;

        public Decryptor(Encoding enc)
        {
            this.enc = enc;
            // инициализируем RSA
            rsaProvider = new RSACryptoServiceProvider();
        }

        public Decryptor(string xmlPrivateKey, Encoding enc)
            : this(enc)
        {
            rsaProvider.FromXmlString(xmlPrivateKey);
        }

        public string GetPublicKey()
        {
            return rsaProvider.ToXmlString(false);
        }

        public string GetPrivateKey()
        {
            return rsaProvider.ToXmlString(true);
        }

        // дешифрование сообщения
        public string DecryptData(byte[] receiveData)
        {
            //int maxLength = rsaProvider.KeySize / 8 - 42;
            int maxLength = rsaProvider.KeySize / 8;
            int iterCount = receiveData.Length / maxLength;
            List<byte> receiveBytes = new List<byte>(rsaProvider.KeySize / 8 * iterCount);
            for (int i = 0; i < iterCount; i++)
            {
                byte[] tempBytes = new byte[Math.Min(receiveData.Length - i * maxLength, maxLength)];
                Buffer.BlockCopy(receiveData, i * maxLength, tempBytes, 0, tempBytes.Length);
                tempBytes = rsaProvider.Decrypt(tempBytes, false);
                receiveBytes.AddRange(tempBytes);
            }
            return enc.GetString(receiveBytes.ToArray());
        }

        // дешифрование сообщения
        public byte[] Decrypt(byte[] receiveData)
        {
            //int maxLength = rsaProvider.KeySize / 8 - 42;
            int maxLength = rsaProvider.KeySize / 8;
            int iterCount = receiveData.Length / maxLength;
            List<byte> receiveBytes = new List<byte>(rsaProvider.KeySize / 8 * iterCount);
            for (int i = 0; i < iterCount; i++)
            {
                byte[] tempBytes = new byte[Math.Min(receiveData.Length - i * maxLength, maxLength)];
                Buffer.BlockCopy(receiveData, i * maxLength, tempBytes, 0, tempBytes.Length);
                tempBytes = rsaProvider.Decrypt(tempBytes, false);
                receiveBytes.AddRange(tempBytes);
            }
            return receiveBytes.ToArray();
        }
    }
}
